<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\Random;
use \app\common\model\FttuserToken;
use \app\common\model\JwuserToken;

/**
 * Token接口
 */
class Token extends Api
{
    protected $noNeedLogin = ['add','jw_add'];
    protected $noNeedRight = '*';

    /**
     * 检测Token是否过期
     *
     */
    public function check()
    {
        $token = $this->auth->getToken();
        $tokenInfo = \app\common\library\Token::get($token);
        $this->success('', ['token' => $tokenInfo['token'], 'expires_in' => $tokenInfo['expires_in']]);
    }

    /**
     * 刷新Token
     *
     */
    public function refresh()
    {
        //删除源Token
        $token = $this->auth->getToken();
        \app\common\library\Token::delete($token);
        //创建新Token
        $token = Random::uuid();
        \app\common\library\Token::set($token, $this->auth->id, 2592000);
        $tokenInfo = \app\common\library\Token::get($token);
        $this->success('', ['token' => $tokenInfo['token'], 'expires_in' => $tokenInfo['expires_in']]);
    }

    // 添加 token
    public function add()
    {
        $user_id = $this->request->post("user_id");//用户id
        $token = $this->request->post("token");//token
        if(!$token || !$user_id){
            $this->error("参数不能为空");
        }

        $user_token = (new FttuserToken())->where(['user_id'=>$user_id])->find();
        if (empty($user_token)) {
            $result = (new FttuserToken())->save(['user_id'=> $user_id, 'token'=>$token]);
        } else {
            $result = $user_token->save(['user_id'=> $user_id, 'token'=>$token]);
        }

        if ($result) {
            $this->success('成功', $result);
        } else {
            $this->error("失败");
        }

    }

    
    // 添加 token
    public function jw_add()
    {
        $user_id = $this->request->post("user_id");//用户id
        $token = $this->request->post("token");//token
        if(!$token || !$user_id){
            $this->error("参数不能为空");
        }
        $user_token = (new JwuserToken())->where(['user_id'=>$user_id])->find();
        if (empty($user_token)) {
            $result = (new JwuserToken())->save(['user_id'=> $user_id, 'token'=>$token]);
        } else {
            $result = $user_token->save(['user_id'=> $user_id, 'token'=>$token]);
        }
        if ($result) {
            $this->success('成功', $result);
        } else {
            $this->error("失败");
        }
    }
}
